package com.dengyin2000.javaeye.ordering.action;

import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

import com.dengyin2000.javaeye.ordering.entity.Role;
import com.dengyin2000.javaeye.ordering.entity.User;


@Name("authenticator")
public class Authenticator
{
    @Logger Log log;
    
    @In Identity identity;
    
    @In(value="orderingDatabase")
    Session session;
    
    @Out(required=false, scope=ScopeType.SESSION)
    User currentUser;
   
    public boolean authenticate()
    {
        log.info("authenticating #0", identity.getUsername());
        //write your authentication logic here,
        //return true if the authentication was
        //successful, false otherwise
//        identity.addRole("admin");
        Query query = session.createQuery("from User where loginName=:name and password=:password");
        query.setString("name", identity.getUsername());
        query.setString("password", identity.getPassword());
        currentUser = (User) query.uniqueResult();
        if (currentUser == null)
        	return false;
        Set<Role> roles = currentUser.getRoles();
        if (roles != null) {
        	for (Role role : roles) {
				identity.addRole(role.getRoleName());
			}
        }
        return true;
    }
}
